<template>
  <div>
    <el-tag
      v-for="(tag,index) in dynamicTags"
      :key="index"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >{{ tag }}</el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" style="marginLeft:5px;" @click="showInput">+ 添加标签</el-button>
  </div>
</template>

<script>
export default {
  props: ['tags'],
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  watch: {
    tags(newName, oldName) {
      this.dynamicTags =
        this.$props.tags === '' ? [] : this.$props.tags.split(',')
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      let result = this.dynamicTags.length ? this.dynamicTags.join(',') : '';
      this.$emit('changeLabel', result)
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
        let result = this.dynamicTags.length ? this.dynamicTags.join(',') : '';
        this.$emit('changeLabel', result)
      }
      this.inputVisible = false
      this.inputValue = '';
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
